package com.zzs.server.service.impl;

import com.zzs.common.core.enums.ResponseCode;
import com.zzs.common.core.enums.UserRole;
import com.zzs.common.security.exception.ServiceException;
import com.zzs.common.security.service.TokenService;
import com.zzs.common.security.util.PasswordUtil;
import com.zzs.server.dao.mysql.AdminMapper;
import com.zzs.server.entity.mysql.AdminDO;
import com.zzs.server.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zzs
 * @date 2025/03/17
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private TokenService tokenService;

    @Override
    public String login(String account, String password) {
        AdminDO adminDO = adminMapper.get(account);
        if (adminDO == null) {
            throw new ServiceException(ResponseCode.INVALID_CREDENTIALS);
        }
        if (!PasswordUtil.matchesPassword(password, adminDO.getPassword())) {
            throw new ServiceException(ResponseCode.INVALID_CREDENTIALS);
        }
        return tokenService.createToken(adminDO.getId(), UserRole.ADMIN);
    }

    @Override
    public void logout(long adminId) {
        tokenService.removeCache(adminId);
    }
}
